'use strict'

//node: 开头表示导入Node.js官方模块
const http = require('node:http')

let serv = http.createServer((req, res) => {
  //输出测试
  console.log(req.headers, req.method, req.url)

  req.on('error', err => {
    console.error(err)
    //出错则销毁连接
    !res.destroyed && res.destroy()
  })

  let bodyLength = 0
  let bodyBuffers = []
  let bodyData = null

  //接收body数据，data 是Buffer实例
  req.on('data', data => {
    bodyBuffers.push(data)
    bodyLength += data.length
  })

  req.on('end', () => {
    if (bodyLength > 0) {
      bodyData = Buffer.concat(bodyBuffers, bodyLength)
      //不再引用开始的buffers，这些数据后续会被垃圾回收
      bodyBuffers = []
    }
    //后续处理：提交数据原样返回
    let ctype = req.headers['content-type']
    if (ctype) {
      res.setHeader('content-type', ctype)
    }
    res.end(bodyData)
  })

})

serv.listen(3003)
